package com.flot.yazb.widget.GiftView;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.flot.yazb.R;
import com.flot.yazb.base.BApplication;
import com.flot.yazb.model.other.GifeModel;
import com.flot.yazb.model.user.UserModel;
import com.flot.yazb.widget.utils.GlideImageLoaderUtil;
import com.flot.yazb.widget.RoundedImageView;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 礼物展示特效控制器
 * Created by fengdongfei on 2017/9/6.
 */

public class GiftManage {
    private Context mContext;
    private LinearLayout giftContainer;//礼物的容器
    private TranslateAnimation inAnim;//礼物View出现的动画
    private AnimationSet outAnim;//礼物View消失的动画
    private ScaleAnimation giftNumAnim;//修改礼物数量的动画
    private LinkedBlockingQueue<GifeModel> queue;//礼物的队列
    private final static int SHOW_GIFT_FLAG = 1;//显示礼物
    private final static int GET_QUEUE_GIFT = 0;//从队列中获取礼物
    private final static int REMOVE_GIFT_VIEW = 2;//当礼物的View显示超时，删除礼物View
    private Timer timer;//轮询礼物容器的所有的子View判断是否超过显示的最长时间
    private UserModel selfModel = BApplication.getInstance().getUserModel();

    public GiftManage(Context context, final LinearLayout giftContainer) {
        this.mContext = context;
        this.giftContainer = giftContainer;
        queue = new LinkedBlockingQueue<GifeModel>(100);
        inAnim = (TranslateAnimation) AnimationUtils.loadAnimation(mContext, R.anim.gift_in);
        outAnim = (AnimationSet) AnimationUtils.loadAnimation(mContext, R.anim.gift_out);
        giftNumAnim = (ScaleAnimation) AnimationUtils.loadAnimation(mContext, R.anim.gift_num);

        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                int count = giftContainer.getChildCount();
                for (int i = 0; i < count; i++) {
                    View view = giftContainer.getChildAt(i);
                    TextView name = (TextView) view.findViewById(R.id.name);
                    long nowtime = System.currentTimeMillis();
                    long upTime = (long) name.getTag();
                    if ((nowtime - upTime) >= 3000) {
                        Message msg = new Message();
                        msg.obj = i;
                        msg.what = REMOVE_GIFT_VIEW;
                        handler.sendMessage(msg);
                    }
                }
            }
        };
        timer = new Timer();
        timer.schedule(task, 2000, 2000);
    }


    //开始显示礼物
    public void showGift() {
        handler.sendEmptyMessageDelayed(GET_QUEUE_GIFT, 1000);//从队列中获取礼物
    }

    //放入礼物到队列
    public boolean addGift(GifeModel vo) {
        return queue.add(vo);
    }


    /**
     * 礼物动画开始，创建view
     */
    public void createAnimalView(GifeModel model, Context context, int num) {
        queue.poll();
        View giftView = LayoutInflater.from(context).inflate(R.layout.gift_item, null);
        giftView.setTag(selfModel.id);
        giftView.findViewById(R.id.iv_present).setTag(num);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.gravity = Gravity.LEFT;//因为是动态添加的布局,所以要代码设置其在父层右边,为初始布局,不然最终一直跑到左边
        lp.topMargin = 5;
        giftView.setLayoutParams(lp);

        //显示礼物的数量
        final MagicTextView giftNum = (MagicTextView) giftView.findViewById(R.id.gift_num);
//        giftNum.setTag(num);
        giftNum.setPadding(0, 10, 0, 0);
        giftNum.setText("X" + num);

        TextView tv = (TextView) giftView.findViewById(R.id.name);
        tv.setText(model.name);
        tv.setTag(System.currentTimeMillis());

        TextView tv_msg = (TextView) giftView.findViewById(R.id.tv_msg);
        tv_msg.setText(model.msg);

        RoundedImageView iv_icon = (RoundedImageView) giftView.findViewById(R.id.iv_icon);
        GlideImageLoaderUtil.loadImage(iv_icon, model.thumb, R.mipmap.activity_splash_background);

        ImageView iv_present = (ImageView) giftView.findViewById(R.id.iv_present);
        iv_present.setBackgroundResource(SendGiftDialog.present_1evel[Integer.parseInt(model.gift_id)]);

        giftContainer.addView(giftView);
        giftView.startAnimation(inAnim);//播放礼物View出现的动
        inAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                giftNum.startAnimation(giftNumAnim);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
    }


    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_GIFT_FLAG://如果是处理显示礼物的消息,显示礼物
                    GifeModel showVo = (GifeModel) msg.obj;
                    int num = showVo.num;
                    //根据userid判断是否存在,如果为空,则重新创建一个否则改变数量
                    View giftView = giftContainer.findViewWithTag(selfModel.id);
                    giftNumAnim.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            handler.sendEmptyMessageDelayed(GET_QUEUE_GIFT, 1000);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {
                        }
                    });

                    //新的礼物不存在
                    if (giftView == null) {
                        createAnimalView(showVo, mContext, num);

                    } else {//如果送的礼物正在显示（只是修改下数量）
                        queue.poll();
                        final MagicTextView giftNum = (MagicTextView) giftView.findViewById(R.id.gift_num);
                        int showNum = (int) num;
                        giftNum.setText("X" + (showNum));
                        giftNum.setTag(showNum);

                        TextView tv = (TextView) giftView.findViewById(R.id.name);
                        tv.setTag(System.currentTimeMillis());

                        TextView tv_msg = (TextView) giftView.findViewById(R.id.tv_msg);
                        tv_msg.setText(showVo.msg);

                        ImageView iv_present = (ImageView) giftView.findViewById(R.id.iv_present);
                        iv_present.setBackgroundResource(SendGiftDialog.present_1evel[Integer.parseInt(showVo.gift_id)]);
                        iv_present.setTag(num);

                        giftNum.startAnimation(giftNumAnim);

                    }
                    break;
                case GET_QUEUE_GIFT://如果是从队列中获取礼物实体的消息,从队列中获取礼物
                    GifeModel vo = queue.peek();
                    if (vo != null) {//如果从队列中获取的礼物不为空，那么就将礼物展示在界面上
                        Message giftMsg = new Message();
                        giftMsg.obj = vo;
                        giftMsg.what = SHOW_GIFT_FLAG;
                        handler.sendMessage(giftMsg);
                    } else {
                        handler.sendEmptyMessageDelayed(GET_QUEUE_GIFT, 1000);//如果这次从队列中获取的消息是礼物是空的，则一秒之后重新获取
                    }
                    break;

                case REMOVE_GIFT_VIEW://当礼物的View显示超时，删除礼物View
                    final int index = (int) msg.obj;
                    View removeView = giftContainer.getChildAt(index);
                    outAnim.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            new Handler().post(new Runnable() {
                                public void run() {
                                    if (giftContainer != null) {
                                        giftContainer.removeViewAt(index);
                                        if (mResetListener != null)
                                            mResetListener.reset();
                                    }
                                }
                            });
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {
                        }
                    });
                    if (removeView != null) {
                        removeView.startAnimation(outAnim);
                    }

                    break;
                default:
                    break;
            }
        }
    };

    private static ResetNum mResetListener;

    interface ResetNum {
        void reset();
    }

    public static void setResetListener(ResetNum listener) {
        mResetListener = listener;
    }

}
